<template>
  <div class="search">
    <input
      @blur="handleBlur"
      @focus="handleFocus"
      v-model="keyWord"
      class="search-input"
      type="text"
      placeholder="输入城市名称或拼音"
    >
    <div class="input-box" v-show="keyWord" ref="wrapper">
      <ul>
        <li class="item border-bottom" @click="handleCityButton(item.name)" v-for="item in resultList" :key="item.id">{{item.name}}</li>
        <li class="item border-bottom" v-show="!resultList.length">未找到匹配城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  data () {
    return {
      keyWord: '',
      resultList: [],
      timer: null
    }
  },
  props: ['cities'],
  watch: {
    keyWord (value) {
      this.timer || clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.resultList = []
        for (let k in this.cities) {
          this.cities[k].forEach(item => {
            if (item.spell.indexOf(value) > -1 || item.name.indexOf(value) > -1) {
              this.resultList.push(item)
            }
          })
        }
      }, 100)
    }
  },
  methods: {
    handleBlur () {
      this.$emit('inputStatus', true)
    },
    handleFocus () {
      this.$emit('inputStatus', false)
    },
    handleCityButton (city) {
      this.changeCity(city)
      this.$router.push('/')
    },
    // 直接把mapMutations映射到这里
    ...mapMutations(['changeCity'])
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper, {click: true})
  }
}
</script>

<style lang="stylus" scoped>
  @import "~_styles/varibles.styl"
  .search
    height: .72rem
    padding: 0 .1rem
    background-color: $bgColor
    .search-input
      box-sizing: border-box
      width: 100%
      height: .62rem
      line-height: .62rem
      padding: 0 .1rem
      border-radius: .1rem
      color: #666
    .input-box
      position: absolute
      top: 1.58rem
      left: 0
      bottom: 0
      right: 0
      overflow: hidden
      background-color: #fff
      z-index: 1
      .item
        line-height: .76rem
        padding-left: .2rem
</style>
